<template>
	<view style="height: 100%;">
		<el-table ref="multipleTable" :data="tableData.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
		 tooltip-effect="dark" style="width: 100%">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="left" block class="table-expand">
						<el-form-item label="项目经验">
							<rich-text :nodes="props.row.projectExperience | $_base64toUtf8"></rich-text>
						</el-form-item>
						<el-form-item label="个人简历">
							<rich-text :nodes="props.row.individualResume | $_base64toUtf8"></rich-text>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column label="日期">
				<template slot-scope="scope">{{ scope.row.time | $_formatDate }}</template>
			</el-table-column>
			<el-table-column prop="username" label="姓名">
			</el-table-column>
			<el-table-column prop="phone" label="电话">
			</el-table-column>
			<el-table-column prop="QQ" label="QQ">
			</el-table-column>
			<el-table-column prop="university" label="学校" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="college" label="学院" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="role" label="角色" show-overflow-tooltip>
			</el-table-column>
			<el-table-column align="right">
				<template slot="header" slot-scope="scope">
					<el-input v-model="search" size="mini" placeholder="输入队友名字" />
				</template>
				<template slot-scope="scope">
					<template v-if="createProjectData.partners">
						<block v-for="(item,index) in createProjectData.partners" :key="index">
							<template v-if="scope.row._id === item._id && item.burdenModule">
								<el-button  type="text" size="mini" @click="handleCheckTask(item,index)">查看任务</el-button>
								<el-button style="color: #F56C6C;" type="text" size="mini" @click="handleEditTask(item,index)">重新分配</el-button>
							</template>
							<el-button v-if="scope.row._id === item._id && !item.burdenModule" type="primary" size="mini" @click="allotProjectModule(scope.$index,scope.row)">分配任务</el-button>
						</block>
					</template>
					<el-button v-else type="primary" size="mini" @click="allotProjectModule(scope.$index,scope.row)">分配任务</el-button>
				</template>
			</el-table-column>
		</el-table>
		
		<!-- 模块 -->
		<el-drawer
		  title="请选择模块分配任务"
		  :visible.sync="drawer"
		  :direction="direction"
		  :before-close="handleClose">
		  <div class="zt-trees custom-scrollbar">
			  	<el-tree
			  	  :data="createProjectData.module"
			  	  show-checkbox
			  	  default-expand-all
				  node-key="id"
			  	  ref="tree"
			  	  highlight-current
			  	  :props="defaultProps">
			  	</el-tree>
			  	<div class="demo-drawer__footer">
			  		<el-button type="primary" @click="getCheckedNodes">确定</el-button>
			  	<el-button @click="resetChecked">重置</el-button>
			  	</div>
			  <div style="margin-top: 20px;text-align: right;">
				  <el-link type="primary" @click="allotModuleHelp">点击查看如何正确分配任务模块</el-link>
			  </div>
		  </div>
		</el-drawer>
		
		<el-drawer
		  :title="`队友${curPartnerData.username}项目任务是。`"
		  :visible.sync="checkCurTaskDrawer"
		  :direction="direction"
		  :before-close="handleCheckCurTaskClose">
		  <div class="zt-trees custom-scrollbar">
			   <el-tree :data="checkCurTask" :props="defaultProps" default-expand-all></el-tree>
		  </div>
		</el-drawer>
		
		<el-dialog title="如何正确分配任务模块" :visible.sync="dialogVisible">
			<el-card class="box-card">
			  <div slot="header" class="clearfix">
				<span class="el-icon-circle-check" style="color: #67C23A;"></span>
			    <span>1、可以直接勾选一级标题，子标题会自动选中</span>
			  </div>
			  <el-image src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-partneronlinedocadmin/9ea1aee0-a706-11ea-8a36-ebb87efcf8c0.png"></el-image>
			</el-card>
		    <el-card class="box-card">
		      <div slot="header" class="clearfix">
				<span class="el-icon-circle-check" style="color: #67C23A;"></span>
		        <span>2、可以直接勾选二级标题（此时一级标题是选中状态里面是一条横线）</span>
		      </div>
		      <el-image src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-partneronlinedocadmin/9e9ec8b0-a706-11ea-b43d-2358b31b6ce6.png"></el-image>
		    </el-card>
			<el-card class="box-card">
			  <div slot="header" class="clearfix">
				<span class="el-icon-circle-close" style="color: #F56C6C;"></span>
			    <span>3、错误操作（不可以勾选二级标题的子标题，如果勾选请全部选中）</span>
			  </div>
			  <el-image src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-partneronlinedocadmin/9eae5910-a706-11ea-8a36-ebb87efcf8c0.png"></el-image>
			</el-card>
		</el-dialog>
	</view>
</template>

<script>
	import {mapState,mapMutations} from "vuex"
	export default {
		data() {
			return {
				curPartnerIndex:-1,
				curPartnerData:{},
				tableData:[],
				search: '',
				drawer: false,
				direction: 'ltr',
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				dialogVisible:false,
				// 查看已经分配的任务
				checkCurTask:[],
				checkCurTaskDrawer:false,
				// 编辑任务
				editTasks:[]
			}
		},
		computed:{
			...mapState(['createProjectData'])
		},
		created() {
			this.curPageData()
		},
		methods: {
			...mapMutations(['createProject']),
			async curPageData() {
				let userIDs = [];
				this.createProjectData.project.applyPerson.forEach(item=>{
					if(item.opinion == 1){
						userIDs.push(item.userID)
					}
				})
				userIDs.push(this.createProjectData.project.userID) // 负责人
				let res = await this.$network({
					cloudName: this.$partnerOnlineCloud,
					api: "getUserinfo",
					data: {
						userID: userIDs
					}
				})
				if (res.status === 0) {
					this.tableData = res.data.map(item=>{
						this.createProjectData.project.userID === item.userID ? item.role = '负责人' : item.role = '队友';
						return item;
					})
				}
			},
			
			// 选择分配模块 
			getCheckedNodes() {
				let {curPartnerIndex,curPartnerData} = this;
				let curTreeData = this.createProjectData.module;
				let checkedData = this.$refs.tree.getCheckedNodes();
				if(checkedData.length <= 0){
					this.$message({
						showClose: true,
						duration:2000,
						message: '请选择需要分配的模块!',
						type: 'warning'
					});
					return false;
				}
				let newTreeData = [];
				let newTreeChildren = [];
				
			    curTreeData.forEach((treeData,treeIndex1)=>{
					checkedData.forEach((checkedData1,checkIndex1)=>{
						// 获取一级标题（说明有一级模块）
						if(treeData.label === checkedData1.label){ 
							// 循环二级模块（一级模块存在的情况下查找二级模块内容）
							newTreeChildren = [];
							curTreeData[treeIndex1].children.forEach((treeChildData,treeChildIndex)=>{
								checkedData.forEach((checkedData2,checkIndex2)=>{  // 二级标题
									if(treeChildData.label === checkedData2.label){
										newTreeChildren.push(checkedData2)
										
										// 删除二级模块子内容
										if(checkedData2.children.length > 0){
											treeChildData.children.forEach((tD,tI)=>{
												checkedData.forEach((cD,cI)=>{
													if(tD.label === cD.label){
														checkedData.splice(cI,1)
													}
												})
											})
										}
										//删除二级模块
										checkedData.splice(checkIndex2,1)
									}
								})
							})
							newTreeData.push({
								id:treeData.id,
								label:treeData.label,
								children:newTreeChildren
							})	
							
							// 删除一级模块
							checkedData.splice(checkIndex1,1);
						}
					})
				})
				
				// 此时checkedData仅剩下没有选择父级元素的内容（注意不能·单独选择 三级小标题）
				 curTreeData.forEach((tD,tI)=>{
					newTreeChildren = [];
					tD.children.forEach((tDchile,tIchile)=>{  // 此时只循环二级模块
						checkedData.forEach((cD,cI)=>{
							if(tDchile.label === cD.label){
								newTreeChildren.push(cD);
								
								// 同样删除二级模块的子内容
								if(cD.children.length>0){
									tDchile.children.forEach((tDchileD,tIchileI)=>{
										checkedData.forEach((cDd,cIi)=>{
											if(tDchileD.label === cDd.label){
												checkedData.splice(cIi,1);
											}
										})
									})
								}
								// 删除二级模块
								checkedData.splice(cI,1);
							}
						})
					}) 
					
					if(newTreeChildren.length > 0){
						newTreeData.push({
							id:tD.id,
							label:tD.label,
							children:newTreeChildren
						})
					}
				 })
				
				// 进行排序
				newTreeData = newTreeData.sort((item1,item2)=>parseInt(item1.id)-parseInt(item2.id));
				if(checkedData.length > 0){
					this.$message({
						showClose: true,
						duration:2000,
						message: '请正确分配模块!',
						type: 'warning'
					});
				} else {
					
					// 临时保存
					if(!this.createProjectData.partners){  // 没有数据
						this.tableData[curPartnerIndex].burdenModule = newTreeData;
						this.createProjectData.partners = this.tableData;
					} else {
						this.createProjectData.partners.forEach((item,index)=>{
							if(item._id === curPartnerData._id){
								this.createProjectData.partners[index].burdenModule =newTreeData;
							}
						})
					}
					this.createProject({
						key: 'partners',
						val: this.createProjectData.partners
					})
					
					//提示
					this.$message({
						showClose: true,
						duration:2000,
						message: `已为${curPartnerData.username}分配项目任务`,
						type: 'success'
					})
					this.drawer = false;
					this.$refs.tree.setCheckedKeys([]); 
				}
			},
			allotModuleHelp(){
				this.dialogVisible = true;
			},
			// 查看分配的任务
			handleCheckTask(item,index){
				this.checkCurTask = item.burdenModule;
				this.curPartnerData = item;
				this.checkCurTaskDrawer = true;
			},
			handleCheckCurTaskClose(done){
				done()
			},
			// 修改分配的任务
			handleEditTask(item,index){
				this.allotProjectModule(index,item)
				// 防止DOM没完全渲染
				this.$nextTick(()=>{
					this.iteratorTree(this.$refs.tree,item.burdenModule)
				})
			},
			// 广度优先遍历树结构JSON,为tree赋值
			iteratorTree(tree,treeNodes){
				if(!treeNodes || !treeNodes.length) return;
				let stack = [];
				//遍历第一层节点 并入栈
				treeNodes.forEach(tree=>{
					stack.push(tree);
				})
				let item;
				while(stack.length){
					item = stack.shift();
					// 给树赋值
					tree.setChecked(item,true,false);
					// 遍历子节点(如果有入栈)
					if(item.children && item.children.length){
						stack = stack.concat(item.children);
					}
				}
			},
			resetChecked() {
				this.$confirm('重置将会清空您之前的选项，确认清空吗？', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
				   this.$refs.tree.setCheckedKeys([]);
				}).catch(() => {});
				
			},
			allotProjectModule(index,item){
				this.curPartnerIndex = index;
				this.curPartnerData = item;
				this.drawer = true;
			},
			handleClose(done) {
				this.$confirm('确认放弃分配模块，将会清空您之前的选择？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
				   this.$refs.tree.setCheckedKeys([]);
				   done();
				}).catch(() => {});
			}
		}
	}
</script>

<style lang="scss">
	.table-expand {
		.el-form-item {
			color: #CCCCCC !important;
			.el-form-item__label {
				width: 90px;
				color: $uni-text-color !important;
			}
		}
	}
	.zt-trees{
		position: absolute;
		top: 80px;
		left: 20px;
		right: 20px;
		bottom: 10px;
	}
	.demo-drawer__footer{
		margin-top: 20px;
	}
	.box-card{
		margin-top: 20px;
	}
</style>
